<?php

namespace app\admin\controller\xapply;

use app\common\controller\Backend;
use app\admin\model\xapply\App;
use app\admin\model\xapply\Rule as RuleModel;

class Rule extends Backend
{

    public function add($ids = null, $type = null){
        $row = App::get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $app_id = $row['id'];
        if ($this->request->isPost()) {
            $user_id = $this->request->post('user_id');
            $dept_id = $this->request->post('dept_id');
            $group_id = $this->request->post('group_id');
            RuleModel::destroy(function($query) use ($type, $app_id){
                $query->where('app_id', $app_id)->where('type', $type);
            });
            $bool = false;
            $a = $this->save($user_id, $type, $app_id, 'user_id');
            if ($a){
                $bool = true;
            }
            $b = $this->save($dept_id, $type, $app_id, 'dept_id');
            if ($b){
                $bool = true;
            }
            $c = $this->save($group_id, $type, $app_id, 'group_id');
            if ($c){
                $bool = true;
            }
            $arr = ['is_use', 'is_notice', 'is_admin'];
            $field = $arr[$type];
            $row->$field = $bool ? 1 : 0;
            $row->save();
            $this->success();
        }
        $this->view->assign('row', $row);
        $this->view->assign('user_id', $this->value($type, $app_id, 'user_id'));
        $this->view->assign('dept_id', $this->value($type, $app_id, 'dept_id'));
        $this->view->assign('group_id', $this->value($type, $app_id, 'group_id'));
        return $this->view->fetch();
    }

    private function value($type, $app_id, $field){
        $arr = RuleModel::where('app_id', $app_id)->where('type', $type)->where($field, '>', 0)->column($field);
        if ($arr){
            return implode(',', $arr);
        }
        return '';
    }

    private function save($id, $type, $app_id, $field){
        $id = trim($id);
        if ($id){
            $query = [];
            $arr = explode(',', $id);
            foreach ($arr as $value){
                $query[] = [
                    'app_id' => $app_id,
                    $field => $value,
                    'type' => $type,
                ];
            }
            if ($query){
                $object = new RuleModel;
                $object->saveAll($query);
                return true;
            }
        }
        return false;
    }
}
